﻿using d1Common;
using d1Common.WebController;
using d1Project.Modules.Common.do4A.Domain;
using d1Project.Tools.PagedList;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/MyUser1")]
    public class MyUser1Controller : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        public async Task<IHttpActionResult> Get([FromUri]MyUser1GetVm model)
        {
            if (string.IsNullOrEmpty(this.DeptId)) this.Error("当前用户未包含部门信息");

            string fileLongPath = doServices.Instance.DoStorage.getAccessUrl("");

            if (string.IsNullOrEmpty(model.DeptId)) model.DeptId = this.DeptId;

            var entities = db.User1s.AsQueryable();
            //查看子部门
            if (model != null && model.IsLookChildren == "1")
            {
                var dept = await db.Depts.FindAsync(model.DeptId);
                var deptIds = await db.Depts.Where(t => t.Path.StartsWith(dept.Path)).Select(t => t.Id).ToListAsync();
                entities = entities.Where(t => deptIds.Contains(t.DeptId));
            }
            //不查看子部门
            else
            {
                entities = entities.Where(t => t.DeptId == model.DeptId);
            }
            //名称搜索
            if (model != null && string.IsNullOrEmpty(model.Name))
            {
                entities = entities.Where(t => t.Name.Contains(model.DeptId));
            }

            var result = await entities.OrderBy(t => t.CreateTime).Select(t => new
            {
                t.Id,
                t.Code,
                t.Name,
                t.PinYin,
                t.Icon,
                Iconlong = fileLongPath + t.Icon,
                t.CreateTime
            }).ToPagedListAsync(model);
            return Ok(result);
        }
    }

    public class MyUser1GetVm : VmBase
    {
        /// <summary>
        /// 部门Id
        /// </summary>
        public string DeptId { get; set; }

        /// <summary>
        /// 是否查看子部门（0否，1是， 默认0)
        /// </summary>
        public string IsLookChildren { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
    }
}
